// import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken() || null,
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  // 设置token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 删除token
  removeToken(state) {
    state.token = null // 删除vuex的token
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 删除用户信息
  reomveUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async userLogin(ctx, data) {
    const [err, res] = await login(data)
    if (err) {
      console.log(err)
    } else {
      // console.log(res)
      ctx.commit('setToken', res)
    }
  },
  // 获取用户资料action
  async getUserInfo(context) {
    const [, res] = await getUserInfo()
    const [, resImg] = await getUserDetailById(res.userId) // 为了获取头像
    // console.log(resImg)
    context.commit('setUserInfo', { ...res, ...resImg })
    return res
  },
  // 登出
  logout(context) {
    // 清除token
    context.commit('removeToken')
    // 清除用户信息
    context.commit('reomveUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

